<?php

namespace Modules\Admin\Http\Controllers\Ebooks;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\AdminLog;
use Modules\Common\Models\Ebooks;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;


class Retrieve
{

    /**
     * @Route(path=/api/admin/ebook)
     */
    public function retrieve()
    {
        $query = Ebooks::with(['category', 'adminUser']);

        //书名
        if (request('book_name')) {
            $query->where('book_name', 'like', '%' . request('book_name') . '%');
        }

        //所属分类
        if (request('category_id')) {
            $query->where('category_id', '=', request('category_id'));
        }

        //上下架
        if (request('is_published')) {
            $query->where('is_published', '=', request('is_published'));
        }

        //是否免费
        if (request('is_free')) {
            $query->where('is_free', '=', request('is_free'));
        }

        //作者名称
        if (request('author')) {
            $query->where('author', '=', request('author'));
        }

        $query->orderByRaw('id desc , created_at desc');

        $sidDefault = auth('api')->user()->sid;
        $eidDefault = auth('api')->user()->eid; 
        $data = $query->where('sid',$sidDefault)->where('eid',$eidDefault)->paginate(request('per_page', 15));

        return Api::success($data);
    }
    
    
     /**
     * @Route(path=/api/admin/ebook-list)
     */
    public function index()
    {
        $query = Ebooks::with(['category', 'adminUser']);
        
        if (request('ids')) {
            $excludedIds = explode(',', request('ids'));
            $query->whereNotIn('id', $excludedIds);
        }
        //书名
        if (request('book_name')) {
            $query->where('book_name', 'like', '%' . request('book_name') . '%');
        }

        //所属分类
        if (request('category_id')) {
            $query->where('category_id', '=', request('category_id'));
        }

        //上下架
        if (request('is_published')) {
            $query->where('is_published', '=', request('is_published'));
        }

        //是否免费
        if (request('is_free')) {
            $query->where('is_free', '=', request('is_free'));
        }

        //作者名称
        if (request('author')) {
            $query->where('author', '=', request('author'));
        }

        $query->orderByRaw('id desc , created_at desc');

        $sidDefault = auth('api')->user()->sid;
        $eidDefault = auth('api')->user()->eid; 
        $data = $query->where('sid',$sidDefault)->where('eid',$eidDefault)->paginate(request('per_page', 15));

        return Api::success($data);
    }
}